package is.api.demo.rest.server;

import com.alibaba.fastjson.JSONObject;
import is.api.demo.isgateway.utils.IsGateWayStringUtils;
import is.api.demo.rest.core.*;
import is.api.demo.rest.utils.DateUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;
import java.util.Random;

/**********************************************************************
 * &lt;p&gt;文件名：${FILE_NAME} &lt;/p&gt;
 * &lt;p&gt;文件描述：${DESCRIPTION}(接口调用类型)
 * @project_name：funi-platform-talentsplace
 * @author shunyao.zeng
 * @date 2018/1/12 10:38
 * @history
 * @department：政务事业部
 * Copyright ChengDu Funi Cloud Code Technology Development CO.,LTD 2014
 *                    All Rights Reserved.
 */
public abstract class InterfaceUtils {

    //默认编码 成都市
    private static final String DEFAULT_REGIONCODE = "510100";
    //时间戳格式
    private static final String TIMESTAMP_STYLE = "yyyyMMddHHmmss";


    /**
     * 接口调用
     *
     * @param apiUrl     地址
     * @param loginId    账号
     * @param password   密码
     * @param token      token
     * @param apiKey     接口号
     * @param param      参数
     * @param regionCode 数据库分区区域编码
     * @return
     */
    public static HttpServiceResult request(final String apiUrl,
                                            final String loginId,
                                            final String password,
                                            final String token,
                                            final String apiKey,
                                            final Object param,
                                            final String regionCode) throws HttpServiceException {
        try {
            final RestTemplate restTemp = RestTemplateUtils.getRestTemplate(apiUrl);
            //restTemp.getMessageConverters().add();
            // 封装参数
            final HttpRequestBody httpRequestBody = InterfaceUtils.createRequestBody(loginId, password, token, apiKey, param, regionCode);
            System.out.println("========请求对象：" + JSONObject.toJSONString(httpRequestBody));

            //headers
            final HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);

            //HttpEntity
            final HttpEntity<Object> requestEntity = new HttpEntity<Object>(httpRequestBody, requestHeaders);
            // 调用接口
            final HttpResponseBody httpResponseBody = restTemp.postForObject(apiUrl, requestEntity, HttpResponseBody.class);
            System.out.println("========响应对象：" + JSONObject.toJSONString(httpResponseBody));
            if (httpResponseBody != null) {
                if (httpResponseBody.isSuccess()) {
                    return new HttpServiceResult(httpResponseBody.getResult());
                } else {
                    throw new HttpServiceException("接口号" + apiKey + ";" + httpResponseBody.getMessage());
                }
            }
            throw new HttpServiceException(apiKey + ";interface Response body not found");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 创建请求实体
     *
     * @param loginId    账号
     * @param password   密码
     * @param token      token
     * @param apiKey     接口号
     * @param param      参数
     * @param regionCode 数据库分区区域编码
     * @return
     */
    private static final HttpRequestBody createRequestBody(final String loginId,
                                                           final String password,
                                                           final String token,
                                                           final String apiKey,
                                                           final Object param,
                                                           final String regionCode) {
        final HttpRequestBody httpRequestBody = new HttpRequestBody();
        //区域不存在，默认市区库
        httpRequestBody.setRegioncode(IsGateWayStringUtils.hasText(regionCode) ? regionCode : DEFAULT_REGIONCODE);
        httpRequestBody.setData(param);
        final String nonce = new Random().nextInt() + "";
        httpRequestBody.setNonce(nonce);
        httpRequestBody.setApiKey(apiKey);
        httpRequestBody.setLoginid(loginId);
        httpRequestBody.setPassword(password);
        final String timestamp = DateUtils.format(new Date(), TIMESTAMP_STYLE);
        final String authenticationKey = Base64.getEncoder().encodeToString((loginId + ":" + password + ":" + timestamp).getBytes());
        httpRequestBody.setAuthenticationKey(authenticationKey);
        //签名
        final CCSMessageDigest digest = CCSMessageDigest.getInstance();
        String signature = null;
        try {
            signature = digest.getSignature(timestamp, nonce, token);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httpRequestBody.setSignature(signature);
        return httpRequestBody;
    }

    /**
     * 生成签名
     *
     * @param args
     */
    public static void main(String[] args) {
        final String timestamp = DateUtils.format(new Date(), TIMESTAMP_STYLE);
        //授权key
        final String authenticationKey = Base64.getEncoder().encodeToString(("你的接口账号" + ":" + "你的密码" + ":" + timestamp).getBytes());
        System.out.println(authenticationKey);
        //签名
        final CCSMessageDigest digest = CCSMessageDigest.getInstance();
        String signature = null;
        try {
            final String nonce = new Random().nextInt() + "";
            System.out.println(nonce);
            signature = digest.getSignature(timestamp, nonce, "你的token");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(signature);
    }
}
